import 'dart:async';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'permission_helper.dart';

///动态权限检测对话框
class PermissionCheckDialog extends StatefulWidget {
  final List<Permission> permissions;
  final String? title;
  final String? tips;

  const PermissionCheckDialog({
    Key? key,
    required this.permissions,
    this.title,
    this.tips,
  }) : super(key: key);

  static bool isShowingDialog = false;

  static Future<dynamic> dismissPermissionDialog(BuildContext context) async {
    if (isShowingDialog) {
      isShowingDialog = false;
      return Navigator.pop(context);
    }
    return null;
  }

  @override
  State<StatefulWidget> createState() => PermissionCheckDialogState();
}

class PermissionCheckDialogState extends State<PermissionCheckDialog>
    with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    PermissionCheckDialog.isShowingDialog = true;
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
    PermissionCheckDialog.isShowingDialog = false;
  }

  @override
  Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
    if (state == AppLifecycleState.resumed) {
      var hasGranted = await PermissionHelper.instance()
          .checkPermissionsGranted(widget.permissions);
      if (PermissionCheckDialog.isShowingDialog && context.mounted) {
        PermissionCheckDialog.isShowingDialog = false;
        Navigator.pop(context, hasGranted);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    String title = widget.title ?? "权限使用说明";
    String tips = widget.tips ?? "该功能需要您授予相关的权限，才可正常使用";
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        PermissionCheckDialog.dismissPermissionDialog(context);
      },
      child: Scaffold(
        backgroundColor: Colors.black38,
        body: Container(
          alignment: Alignment.topCenter, //Alignment.center,
          padding: const EdgeInsets.only(top: 28),
          child: Container(
            width: double.maxFinite,
            margin: const EdgeInsets.symmetric(horizontal: 16),
            decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(8))),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  width: double.maxFinite,
                  padding: const EdgeInsets.only(left: 16, top: 16, right: 16),
                  child: Text(title,
                      style:
                          const TextStyle(fontSize: 16, color: Colors.black87)),
                ),
                Container(
                  width: double.maxFinite,
                  padding: const EdgeInsets.only(
                      left: 16, top: 4, right: 16, bottom: 20),
                  child: Text(tips,
                      style:
                          const TextStyle(fontSize: 14, color: Colors.black54)),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

///引导设置打开权限对话框
class OpenSettingDialog extends StatefulWidget {
  const OpenSettingDialog({
    Key? key,
    required this.permission,
    this.tips,
  }) : super(key: key);

  final Permission permission;
  final String? tips;

  @override
  State<OpenSettingDialog> createState() => _OpenSettingDialogState();
}

class _OpenSettingDialogState extends State<OpenSettingDialog>
    with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
    if (state == AppLifecycleState.resumed) {
      var hasGranted = await PermissionHelper.instance()
          .checkPermissionsIsGranted(widget.permission);
      if (context.mounted) {
        Navigator.pop(context, hasGranted);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black54,
      body: Center(
        child: Container(
          width: MediaQuery.of(context).size.width - 60,
          decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(8))),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(
                    left: 15, right: 15, top: 30, bottom: 50),
                child: Text(widget.tips ?? "该功能需要到设置中授予相关权限，才可正常使用，请授予应用相关权限",
                    style:
                        const TextStyle(fontSize: 16, color: Colors.black87)),
              ),
              Divider(height: 1, thickness: 1, color: Colors.grey[300]),
              SizedBox(
                height: 45,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Expanded(
                        child: InkWell(
                            onTap: () => Navigator.pop(context, false),
                            child: const Center(
                              child: Text(
                                "取消",
                                style: TextStyle(
                                    fontSize: 16, color: Colors.black54),
                              ),
                            ))),
                    SizedBox(
                      height: 45,
                      width: 1,
                      child: VerticalDivider(
                          width: 1, thickness: 1, color: Colors.grey[300]),
                    ),
                    Expanded(
                        child: InkWell(
                      onTap: () async {
                        await openAppSettings();
                      },
                      child: const Center(
                          child: Text(
                        "去设置",
                        style: TextStyle(fontSize: 16, color: Colors.black87),
                      )),
                    )),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
